/**
 * =================================================
 * Vue2 自动从components目录引入第三方组件导入装载进项目
 * -------------------------------------------------
 * 每个插件 Vue.use 方法需封装在components的各子目录内
 * -------------------------------------------------
 * Author: 曹操<pgcao@qq.com>
 * HomePage: https://gitee.com/pgcao/vue3-vite2-ts
 * =================================================
 */
import Vue from 'vue';
import type { CreateElement, Component } from 'vue';

export default async (app: Component, callbackfn: (Props: any) => void) => {
  let Props = { render: (h: CreateElement) => h(app) };
  console.time('pluginsLoad');
  // 批量装载VUE项目所需组件插件, 即 Vue.use('xxx') 的东西，每个子目录为一个依赖
  const pluginList = import.meta.globEager('./components/*/index.ts');

  await Promise.all(
    Object.values(pluginList).map(async module => {
      if (typeof module.default === 'function') {
        const result = await module.default(Vue);
        if (Object.prototype.toString.call(result) === '[object Object]') {
          Props = Object.assign(Props, result);
        }
      }
    })
  );

  console.timeEnd('pluginsLoad');
  /* @__PURE__ */ //esbuild打包编译时移除
  console.log(`[vite] vue-${Vue.version} plugins done`);

  // 自动装载完成所有插件后再实例化到DOM
  callbackfn.call(null, Props);
};
